/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Manual.java
 *
 * Created on 9/10/2012, 11:02:49 PM
 */
package flujocaja;

import Clases.ModeloPorcentual;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author HP G42
 */
public class Manual extends javax.swing.JDialog {
    
    private double [] datos;

    private boolean porcentajes = false;
    
    /** Creates new form Manual */
    public Manual(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
    public double [] insertarDatosManuales(int [] anios){
        this.setTitle("Insertar datos manuales");
        this.porcentajes = false;
        this.panelRedondear.setVisible(false);
        DefaultTableModel modelo = new DefaultTableModel();
        Object [] fila = new Object[anios.length];
        for (int i=0; i<anios.length; i++){
            modelo.addColumn(anios[i]);
        }
        modelo.addRow(fila);
        this.jTable1.setModel(modelo);
        
        this.setVisible(true);
        return this.datos;        
    }

    public double [] editarDatosManuales(int [] anios, double [] valoresAnteriores){
        this.setTitle("Editar datos manuales");
        this.porcentajes = false;
        this.panelRedondear.setVisible(false);
        DefaultTableModel modelo = new DefaultTableModel();
        Object [] fila = new Object[valoresAnteriores.length];
        
        for (int i=0; i<anios.length; i++){
            modelo.addColumn(anios[i]);
            fila[i] = valoresAnteriores[i];
        }
        modelo.addRow(fila);
        this.jTable1.setModel(modelo);
        
        this.setVisible(true);
        return this.datos;        
    }
    
    public double [] insertarPorcentajes(int [] anios)
    {
        this.setTitle("Lista de porcentajes manuales");
        this.porcentajes = true;
        this.panelRedondear.setVisible(true);
        DefaultTableModel modelo = new DefaultTableModel();
        Object [] fila = new Object[anios.length];
        for (int i=0; i<anios.length; i++){
            modelo.addColumn(anios[i]);
        }
        modelo.addRow(fila);
        this.jTable1.setModel(modelo);
        
        this.setVisible(true);
        return this.datos; 
    }
    
    public double [] editarPorcentajesManuales(int [] anios, double [] valoresAnteriores){
        this.setTitle("Editar lista de porcentajes manuales");
        this.porcentajes = true;
        this.panelRedondear.setVisible(true);
        DefaultTableModel modelo = new DefaultTableModel();
        Object [] fila = new Object[valoresAnteriores.length];
        
        for (int i=0; i<anios.length; i++){
            modelo.addColumn(anios[i]);
            fila[i] = ModeloPorcentual.redondearCifra(valoresAnteriores[i]*100)+"%";
        }
        modelo.addRow(fila);
        this.jTable1.setModel(modelo);
        
        this.setVisible(true);
        return this.datos;        
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        aceptar = new javax.swing.JButton();
        cancelar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        panelRedondear = new javax.swing.JPanel();
        redondear = new javax.swing.JRadioButton();
        noRedondear = new javax.swing.JRadioButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        datosArchivo = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(flujocaja.FlujoCajaApp.class).getContext().getResourceMap(Manual.class);
        aceptar.setText(resourceMap.getString("aceptar.text")); // NOI18N
        aceptar.setName("aceptar"); // NOI18N
        aceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aceptarActionPerformed(evt);
            }
        });

        cancelar.setText(resourceMap.getString("cancelar.text")); // NOI18N
        cancelar.setName("cancelar"); // NOI18N
        cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarActionPerformed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane1.setViewportView(jTable1);

        panelRedondear.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("panelRedondear.border.title"))); // NOI18N
        panelRedondear.setName("panelRedondear"); // NOI18N

        buttonGroup1.add(redondear);
        redondear.setText(resourceMap.getString("redondear.text")); // NOI18N
        redondear.setName("redondear"); // NOI18N

        buttonGroup1.add(noRedondear);
        noRedondear.setSelected(true);
        noRedondear.setText(resourceMap.getString("noRedondear.text")); // NOI18N
        noRedondear.setName("noRedondear"); // NOI18N

        javax.swing.GroupLayout panelRedondearLayout = new javax.swing.GroupLayout(panelRedondear);
        panelRedondear.setLayout(panelRedondearLayout);
        panelRedondearLayout.setHorizontalGroup(
            panelRedondearLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelRedondearLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelRedondearLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(noRedondear)
                    .addComponent(redondear))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        panelRedondearLayout.setVerticalGroup(
            panelRedondearLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelRedondearLayout.createSequentialGroup()
                .addComponent(noRedondear)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(redondear))
        );

        jMenuBar1.setName("jMenuBar1"); // NOI18N

        jMenu1.setText(resourceMap.getString("jMenu1.text")); // NOI18N
        jMenu1.setName("jMenu1"); // NOI18N

        datosArchivo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK));
        datosArchivo.setText(resourceMap.getString("datosArchivo.text")); // NOI18N
        datosArchivo.setName("datosArchivo"); // NOI18N
        datosArchivo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                datosArchivoActionPerformed(evt);
            }
        });
        jMenu1.add(datosArchivo);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addComponent(panelRedondear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(cancelar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(aceptar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelRedondear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(aceptar)
                    .addComponent(cancelar)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarActionPerformed
        // TODO add your handling code here:
        this.datos = null;
        this.dispose();               
    }//GEN-LAST:event_cancelarActionPerformed

    private void datosArchivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_datosArchivoActionPerformed
        // TODO add your handling code here:
        JFileChooser selector = new JFileChooser();
        int resultado = selector.showOpenDialog(null);
        if (resultado==JFileChooser.APPROVE_OPTION){
            this.cargarDatosHistoricos(selector.getSelectedFile().getAbsolutePath());
        }
    }//GEN-LAST:event_datosArchivoActionPerformed

    private void aceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aceptarActionPerformed
        // TODO add your handling code here:
        int size = this.jTable1.getModel().getColumnCount();
        DefaultTableModel modelo = (DefaultTableModel) this.jTable1.getModel();
        this.datos = new double[size];
        for (int i=0; i<size; i++){
            if (!this.porcentajes)
                datos[i] = Double.parseDouble(modelo.getValueAt(0, i).toString());
            else
                datos[i] = ModeloPorcentual.formatearPorcentaje(modelo.getValueAt(0, i).toString(), redondear.isSelected());
        }
        this.dispose();
    }//GEN-LAST:event_aceptarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Manual.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Manual.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Manual.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Manual.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                Manual dialog = new Manual(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton aceptar;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton cancelar;
    private javax.swing.JMenuItem datosArchivo;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JRadioButton noRedondear;
    private javax.swing.JPanel panelRedondear;
    private javax.swing.JRadioButton redondear;
    // End of variables declaration//GEN-END:variables

    private void cargarDatosHistoricos(String direccion) {
        try {
            DefaultTableModel modelo = (DefaultTableModel) this.jTable1.getModel();
            
            FileInputStream origen = new FileInputStream(direccion);
            InputStreamReader conexionArchivo = new InputStreamReader(origen, "ISO-8859-1");
            BufferedReader lectorBuffer = new BufferedReader(conexionArchivo);

            String [] datosHistoricos = lectorBuffer.readLine().split(":");            
            String [] listaDatosHistoricos = datosHistoricos[1].split(",");

            for (int i=0; i<listaDatosHistoricos.length; i++){
                modelo.setValueAt(listaDatosHistoricos[i], 0, i);
            }
            
            origen.close();
            conexionArchivo.close();
            lectorBuffer.close();

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Manual.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Manual.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
                Logger.getLogger(Manual.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
